// 获取请求参数
// 使用示例
// location.href = http://localhost:8080/index.html?id=123
// T.p('id') --> 123;
var url = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
}

//登录token
var token = localStorage.getItem("token");
// var config = localStorage.getItem("config");
if(token == 'null'){
    parent.location.href = 'login.html';
}

//全局配置
$.ajaxSetup({
	dataType: "json",
	cache: false,
    headers: {
        "token": token
    },
    complete: function(xhr) {
        if(xhr.responseJSON.code == 401){
            toUrl('/login.html');
        }
    }
})

//权限判断
function hasPermission(permission) {
    if(isNullOrEmpty(window.parent.perms)) {
    	return false;
    }
	if (window.parent.perms.indexOf(permission) > -1) {
        return true;
    } else {
        return false;
    }
}

toUrl = function(href) {
	window.location.href = href;
}

$.fn.bootstrapTableEx = function(opt){
	var defaults = {
		url: '',
        striped:true,//隔行变色
		dataField: "rows",
		method: 'post',
		dataType: 'json',
		selectItemName: 'id',
		clickToSelect: true,
		pagination: true,
		smartDisplay: false,
		pageSize: 10,
		pageList: [10, 20, 30, 40, 50],
        paginationLoop: false,
		sidePagination: 'server',
		queryParamsType : null,
		columns: [],
        onLoadSuccess:function(){
		    //添加title 鼠标悬停显示
            $('.bootstrap-table tr td').each(function () {
                $(this).attr("title", $(this).text());
            });
        }
	}
	var option = $.extend({}, defaults, opt);
	$(this).bootstrapTable(option);
}

formatDate = function (v, format) {
    if (!v) return "";
    var d = v;
    if (typeof v === 'string') {
        if (v.indexOf("/Date(") > -1)
            d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
        else
            d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0]));//.split(".")[0] 用来处理出现毫秒的情况，截取掉.xxx，否则会出错
    }
    var o = {
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": d.getHours(),
        "m+": d.getMinutes(),
        "s+": d.getSeconds(),
        "q+": Math.floor((d.getMonth() + 3) / 3),
        "S": d.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

isNullOrEmpty = function (obj) {
    if ((typeof (obj) == "string" && obj == "") || obj == null || obj == undefined) {
        return true;
    } else {
        return false;
    }
}

isNotNullOrEmpty = function (obj) {
    if ((typeof (obj) == "string" && obj == "") || obj == null || obj == undefined) {
        return false;
    } else {
        return true;
    }
}

checkedArray = function (id) {
    var isOK = true;
    if (id == undefined || id == "" || id == 'null' || id == 'undefined') {
        isOK = false;
        dialogMsg('您没有选中任何数据项！');
    }
    return isOK;
}

checkedRow = function (id) {
    var isOK = true;
    if (id == undefined || id == "" || id == 'null' || id == 'undefined') {
        isOK = false;
        dialogMsg('您没有选中任何数据项！');
    } else if (id.length > 1) {
        isOK = false;
        dialogMsg('您只能选择一条数据项！');
    }
    return isOK;
}

reload = function () {
    location.reload();
    return false;
}

dialogOpen = function(opt){
    var defaults = {
        id : 'layerForm',
        title : '',
        width: '',
        height: '',
        url : null,
        scroll : true,
        maxmin: true,
        data : {},
        btnAlign:'r',
        btn: ['确定', '取消'],
        btnSize:2,//默认为2个按钮
        success: function(){},
        yes: function(){},
        cancel: function(){}
    }
    var option = $.extend({}, defaults, opt), content = null;
    if(option.scroll){
        content = [option.url]
    }else{
        content = [option.url, 'no']
    }
    /**
     * @Description:目前扩展至能够配置三个按钮
     * @updateTime shusm 2017/11/4 9:58
     */
    if(option.btnSize == 2){
        top.layer.open({
            type : 2,
            id : option.id,
            title : option.title,
            closeBtn : 1,
            anim: -1,
            isOutAnim: false,
            shadeClose : false,
            maxmin: true,
            shade : 0.3,
            area : [option.width, option.height],
            content : content,
            btn: option.btn,
            btnAlign:option.btnAlign,
            success: function(){
                option.success(option.id);
            },
            yes: function(){
                option.yes(option.id);
            }
        });
    }else if(option.btnSize ==3){
        top.layer.open({
            type : 2,
            id : option.id,
            title : option.title,
            closeBtn : 1,
            anim: -1,
            isOutAnim: false,
            shadeClose : false,
            maxmin: true,
            shade : 0.3,
            area : [option.width, option.height],
            content : content,
            btn: option.btn,
            btnAlign:option.btnAlign,
            yes: function(){
                option.yes(option.id);
            },
            btn2:function (index, layero) {
                option.btn2(option.id);
                return false
            },
            btn3: function(index, layero){
                option.cancel(option.id);
            },
            success: function(){
                option.success(option.id);
            }
        });
    }else if(option.btnSize ==1){
        top.layer.open({
            type : 2,
            id : option.id,
            title : option.title,
            closeBtn : 1,
            anim: -1,
            isOutAnim: false,
            shadeClose : false,
            maxmin: true,
            shade : 0.3,
            area : [option.width, option.height],
            content : content,
            btn: '关闭',
            btnAlign:option.btnAlign,
            close: function(index, layero){
                option.cancel(option.id);
            },
            success: function(){
                option.success(option.id);
            }
        });
    }else{
        dialogAlert("目前layer弹窗只支持1,2个或者3个按钮！")
        return false;
    }

}

dialogContent = function(opt){
	var defaults = {
		title : '系统窗口',
		width: '',
		height: '',
		content : null,
		data : {},
		btn: ['确定', '取消'],
		success: null,
		yes: null
	}
	var option = $.extend({}, defaults, opt);
	return top.layer.open({
	  	type : 1,
		title : option.title,
		closeBtn : 1,
		anim: -1,
		isOutAnim: false,
		shadeClose : false,
		shade : 0.3,
		area : [option.width, option.height],
		shift : 5,
		content : option.content,
		btn: option.btn,
		success: option.success,
		yes: option.yes
    });
}

dialogAjax = function(opt){
	var defaults = {
		title : '系统窗口',
		width: '',
		height: '',
		url : null,
		data : {},
		btn: ['确定', '取消'],
		success: null,
		yes: null
	}
	var option = $.extend({}, defaults, opt);
	$.post(option.url, null, function(content){
		layer.open({
		  	type : 1,
			title : option.title,
			closeBtn : 1,
			anim: -1,
			isOutAnim: false,
			shadeClose : false,
			shade : 0.3,
			area : [option.width, option.height],
			shift : 5,
			content : content,
			btn: option.btn,
			success: option.success,
			yes: option.yes
	    });
	});
}

dialogAlert = function (content, type) {
	var msgType = {
		success:1,
		error:2,
		warn:3,
		info:7
	};
	if(isNullOrEmpty(type)){
		type='info';
	}
	top.layer.alert(content, {
        icon: msgType[type],
        title: "系统提示",
        anim: -1,
        btnAlign: 'c',
		isOutAnim: false
    });
}

dialogConfirm = function (content, callBack) {
	top.layer.confirm(content, {
		area: '338px',
		icon: 7,
        anim: -1,
		isOutAnim: false,
        title: "系统提示",
        btn: ['确认', '取消'],
        btnAlign: 'c',
    	yes: callBack
    });
}

dialogMsg = function(msg, type) {
	var msgType = {
		success:1,
		error:2,
		warn:3,
		info:7
	};
	if(isNullOrEmpty(type)){
		type='info';
	}
	top.layer.msg(msg, {
		icon: msgType[type],
		time: 2000
	}); 
}

dialogClose = function() {
	var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	top.layer.close(index); //再执行关闭 
}

dialogLoading = function(flag) {
	if(flag){
		top.layer.load(0, {
			shade: [0.1,'#fff'],
			time: 2000
		});
	}else{
		top.layer.closeAll('loading');
	}
}

$.fn.GetWebControls = function (keyValue) {
    var reVal = "";
    $(this).find('input,select,textarea').each(function (r) {
        var id = $(this).attr('id');
        var type = $(this).attr('type');
        switch (type) {
            case "checkbox":
                if ($("#" + id).is(":checked")) {
                    reVal += '"' + id + '"' + ':' + '"1",'
                } else {
                    reVal += '"' + id + '"' + ':' + '"0",'
                }
                break;
            default:
                var value = $("#" + id).val();
                if (value == "") {
                    value = "&nbsp;";
                }
                reVal += '"' + id + '"' + ':' + '"' + $.trim(value) + '",'
                break;
        }
    });
    reVal = reVal.substr(0, reVal.length - 1);
    if (!keyValue) {
        reVal = reVal.replace(/&nbsp;/g, '');
    }
    reVal = reVal.replace(/\\/g, '\\\\');
    reVal = reVal.replace(/\n/g, '\\n');
    var postdata = jQuery.parseJSON('{' + reVal + '}');
    return postdata;
};

$.fn.SetWebControls = function (data) {
    var $id = $(this)
    for (var key in data) {
        var id = $id.find('#' + key);
        if (id.attr('id')) {
            var type = id.attr('type');
            var value = $.trim(data[key]).replace(/&nbsp;/g, '');
            switch (type) {
                case "checkbox":
                    if (value == 1) {
                        id.attr("checked", 'checked');
                    } else {
                        id.removeAttr("checked");
                    }
                    break;
                default:
                    id.val(value);
                    break;
            }
        }
    }
}

tabiframeId = function () {
    var iframeId = top.$(".DP_iframe:visible").attr("id");
    return iframeId;
}

$.currentIframe = function () {
    var tabId = tabiframeId();
	if(isNullOrEmpty(tabId)) {//单页iframe嵌套
		return $(window.parent.document).contents().find('#main')[0].contentWindow;
    }
    return $(window.parent.document).contents().find('#'+tabiframeId())[0].contentWindow;//多层tab页嵌套
}



/*************************************  扩展js ********************************/
//字符串超出省略 
String.prototype.cutstr = function (len) {
    var restr = this;
    var wlength = this.replace(/[^\x00-\xff]/g, "**").length;
    if (wlength > len) {
        for (var k = len / 2; k < this.length; k++) {
            if (this.substr(0, k).replace(/[^\x00-\xff]/g, "**").length >= len) {
                restr = this.substr(0, k) + "...";
                break;
            }
        }
    }
    return restr;
}
//清除字符串的空格
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, '');
}
// 返回字符串的实际长度, 一个汉字算2个长度
String.prototype.strlen = function () {
    return this.replace(/[^\x00-\xff]/g, "**").length;
}
//替换全部
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2)
}
//分割字符串，如果不存在对应分割标识，不分割（解决多出逗号的情况）
String.prototype.division = function (str) {
    if (this.indexOf(str) > -1) {
        return this.split(str);
    } else {
        return [];
    }
}
//指定元素是否存在数组中
Array.prototype.inArray = function (e) {
    for (i = 0; i < this.length; i++) {
        if (this[i] == e) return true;
    }
    return false;
}
//数组去重
Array.prototype.cleanRepeat = function () {
    var tempArray = this.slice(0); //复制数组到临时数组
    for (var i = 0, l = tempArray.length; i < l; i++) {
        for (var j = i + 1; j < tempArray.length;) {
            //后面的元素若和待比较的相同，则删除并计数；
            //删除后，后面的元素会自动提前，所以指针j不移动
            //不同，则指针移动
            tempArray[j] == tempArray[i] ? tempArray.splice(j, 1) : j++;
        }
    }
    return tempArray;
}
//返回某个值在数组中的位置
Array.prototype.indexOf = function (e) {
    for (var i = 0, l = this.length; i < l; i++) {
        if (this[i] == e) return i;
    }
    return -1;
}
//数组中移除元素
Array.prototype.remove = function (val) {
    var index = -1;
    for (var i = 0, l = this.length; i < l; i++) {
        if (this[i] == val) index = i;
    }
    if (index > -1) {
        this.splice(index, 1);
    }
};

//数组包含
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

// 字符串占位符
// var str2 = "js实现用{1}自符串替换占位符{1} {2}  {0} ".format("I","LOVE","YOU");
// String.prototype.format = function() {
//     if (arguments.length == 0) return this;
//     var param = arguments[0];
//     var s = this;
//     if (typeof(param) == 'object') {
//         for (var key in param)
//             s = s.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
//         return s;
//     } else {
//         for (var i = 0; i < arguments.length; i++)
//             s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
//         return s;
//     }
// };

function StringBuffer() {
    this._strs = new Array;
}
StringBuffer.prototype.append = function (str) {
    this._strs.push(str);
};
StringBuffer.prototype.toString = function() {
    this._strs.join("");
};

//非空校验 strings中的空格，制表符，换页符 会被去掉再校验
function isNotNull(strings) {
    if(strings == undefined){
        return false;
    }
    if (strings.replace(/(^s*)|(s*$)/g, "").length ==0){
        return false;
    }else {
        return true;
    }
}

/*3.用正则表达式实现html转码*/
function htmlEncodeByRegExp(str){
    var s = "";
    if(str == undefined || str.length == 0) return "";
    s = str.replace(/&/g,"&amp;");
    s = s.replace(/</g,"&lt;");
    s = s.replace(/>/g,"&gt;");
    // s = s.replace(/ /g,"");
    s = s.replace(/\'/g,"&#39;");
    s = s.replace(/\"/g,"&quot;");
    s = s.replace(/\n"/g,"");
    s = s.replace(/\r"/g,"");
    return s;
}
/*4.用正则表达式实现html解码*/
function htmlDecodeByRegExp (str){
    var s = "";
    if(str == undefined || str.length == 0) return "";
    s = str.replace(/&amp;/g,"&");
    s = s.replace(/&lt;/g,"<");
    s = s.replace(/&gt;/g,">");
    s = s.replace(/&nbsp;/g," ");
    s = s.replace(/&#39;/g,"\'");
    s = s.replace(/&quot;/g,"\"");
    return s;
}
/*************************************  扩展js ********************************/
//获取根目录 http://localhost:8080/xx
getRootPath = function () {
    var pathName = window.location.pathname.substring(1);
    var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
    if (webName == "") {
        return window.location.protocol + '//' + window.location.host;
    }
    else {
        return window.location.protocol + '//' + window.location.host + '/' + webName;
    }
};